﻿using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Fee.FileAttachs;
using Fee.IO.Importers;
using JwtWebApi.Data;
using JwtWebApi.Models.Manage;
using JwtWebApi.Models.ViewModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace JwtWebApi.Controllers.Manage
{
    [Authorize]
    [Route("manage/[controller]")]
    [ApiController]
    [EnableCors]
    public class OrderContractController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly FileManager _fileManager;
        public OrderContractController(ApplicationDbContext context, FileManager fileManager)
        {
            _context = context;
            _fileManager = fileManager;
            ;
        }

        [HttpGet("list")]
        public IActionResult Index([FromQuery] OrderContractSearch searcher)
        {
            var query = _context.OrderContracts
                .Include(f => f.Project)
                .Include(f => f.FrameworkContract)
                .Include(f => f.Vendor);
            return Json(new
            {
                data = query.Skip(searcher.GetSkip()).Take(searcher.GetTake())
                    .Select(f => new OrderContractViewModel(f)),
                total = query.Count()
            });
        }

        [HttpPost("save")]
        public IActionResult Save([FromBody] OrderContractViewModel contractViewModel)
        {
            var contract = contractViewModel.ToOrderContract(_context);
            if (contract.Id == 0)
                _context.Add(contract);
            else
                _context.Update(contract);
            _context.SaveChanges();
            return Json(new { successed = true });
        }

        [HttpGet("get/{id}")]
        public IActionResult Get(int id)
        {
            var order = _context.OrderContracts
                .Include(f => f.Vendor)
                .Include(f => f.Project)
                .Include(f => f.FrameworkContract)
                .FirstOrDefault(_ => _.Id == id);
            return Json(new OrderContractViewModel(order));
        }

        [HttpPost("Import")]
        public async Task<IActionResult> Post([FromForm] IFormFile formFile)
        {
            // full path to file in temp location
            var filePath = _fileManager.GetTempPrivateFile(Path.GetExtension(formFile.FileName), User.Identity);
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
            }

            var importRowResults = new OrderContractImporter<ApplicationDbContext>(_context, true);
            var isValidate = importRowResults.Import(filePath, out var importResult, out var resultFilePath);
            var message = isValidate ? "导入成功" : "导入失败";
            message += "。请点击结果文件，查看文件导入结果";

            return Json(new
            {
                successed = isValidate,
                resultFilePath,
                message
            });
        }

    }
}